package com.wanxiang.commonlib.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by lgj
 * 2020/5/8
 **/
public class SharePreferenceUtils {

    private static final String TAG = "SharePreferenceUtils";

    /**
     * 保存在手机里面的文件名
     */
    public static final String FILE_NAME = "x7_launcher_data";

    /**
     * 播放模式
     */
    public static final String KEY_PLAYMODE="playMode";

    /**
     * 播放模式,分区二
     */
    public static final String KEY_PLAYMODE_TWO="playMode";


    /**
     * EQ
     */
    public static final String KEY_EQ="eq";

    /**
     * EQ，分区一
     */
    public static final String KEY_EQ_ONE="eq_one";

    /**
     * EQ，分区二
     */
    public static final String KEY_EQ_TWO="eq_two";

    public static final String DISTURB_OPEN_FRONT_VOICE_STATE = "disturb_open_front_voice_state";

    public static final String LOW_POWER_OPEN_FRONT_VOICE_STATE = "low_power_open_front_voice_state";
    public static final String LOW_POWER_OPEN_FRONT_SCREEN_BRIGHTNESS= "low_power_open_front_screen_brightness";
    public static final String LOW_POWER_OPEN_FRONT_SCREENSAVER= "low_power_open_front_screensaver";

    /**
     * 语音唤醒，0，关闭；1，打开
     */
    public static final String VOICE_WEAKUP="weakup";

    /**
     * 低功耗，0，关闭；1，打开
     */
    public static final String LOW_POWER="low_power";

    public static final String IS_VOICE_INIT="voiceinit";  //语音初始化，功能设置模块需要知道当前语音初始化状态，便于切换语音开关

    public static final String MUSIC_INFOS="musicinfos";  //保存音乐列表,用于定时播放

    public static final String IS_DEVICE_FIRST_USE="device_first_use";  //设备是否第一次开机使用
    public static final String IS_WIFI_FIRST_CONNECT="is_wifi_first_connect";  //设备开机后,第一次连接网络


    /**
     * 音源输出，0，本地；3，蓝牙；1，外部
     */
    public static final String MEDIA_OUTPUT="media_output";

    /**
     * 分区一音源输出，0，本地；3，蓝牙；1，外部
     */
    public static final String ONE_SOUND_SOURCE="one_sound_source";

    /**
     * 分区二音源输出，0，本地；3，蓝牙；1，外部
     */
    public static final String TWO_SOUND_SOURCE="two_sound_source";

    /**
     * 音量
     */
    public static final String VOLUME_AREA_ALL="volume_area_all";

    /**
     * 系统音量
     */
    public static final String VOLUME_SYSTEM_SIZE="volume_system_size";

    /**
     * 左声道音量
     */
    public static final String VOLUME_LEFT_ALL="volume_left_all";


    /**
     * 右声道音量
     */
    public static final String VOLUME_RIGHT_ALL="volume_right_all";


    /**
     * 音量，分区一
     */
    public static final String VOLUME_AREA_ONE="volume_area_one";

    /**
     * 左声道音量，分区一
     */
    public static final String VOLUME_LEFT_ONE="volume_left_one";


    /**
     * 右声道音量，分区一
     */
    public static final String VOLUME_RIGHT_ONE="volume_right_one";

    /**
     * 音量，分区二
     */
    public static final String VOLUME_AREA_TWO="volume_area_two";

    /**
     * 左声道音量，分区二
     */
    public static final String VOLUME_LEFT_TWO="volume_left_two";


    /**
     * 右声道音量，分区二
     */
    public static final String VOLUME_RIGHT_TWO="volume_right_two";

    /**
     * 分区一静音前音量
     */
    public static final String VOLUME_AREA_ONE_LAST="volume_area_one_last";

    /**
     * 分区二静音前音量
     */
    public static final String VOLUME_AREA_TWO_LAST="volume_area_two_last";

    /**
     * 分区一设置AUX开前音量
     */
    public static final String VOLUME_AREA_ONE_AUX_LAST="volume_area_one_aux_last";

    /**
     * 分区一名称
     */
    public static final String NAME_AREA_ONE="name_area_one";

    /**
     * 分区二名称
     */
    public static final String NAME_AREA_TWO="name_area_two";


    /**
     * 当前分区
     */
    public static final String AREA_CURRENT="area_current";
    /**
     * 当前联动状态
     */
    public static final String SYNC_CURRENT="sync_current";

    /**
     * 是否亮屏
     */
    public static final String IS_SCREEN_ON="is_screen_on";


    /**
     * 串口ID
     */
    public static final String RS485ID="rs485id";

    /**
     * 波特率
     */
    public static final String BOARDRATE="boardrate";

    /**
     * 房间名称
     */
    public static final String RS485_ROOM_NAME="rs485_room_name";


    /**
     * 咪咕音乐会员状态
     */
    public static final String MIGU_VIP_STATUS="migu_vip_status";

    /**
     * 用户是否已经领取咪咕会员
     */
    public static final String MIGU_VIP_IS_GET="migu_vip_is_get_new_new";

    /**
     * 用户是否已经AI教育授权
     */
    public static final String MIGU_Education_IS_GET="migu_education_is_get_new_new";

    /**
     * AI教育授权状态
     */
    public static final String MIGU_Education_STATUS="migu_education_status";

    /**
     * 更多应用
     */
    public static final String APP_MORE="app_more";

    /**
     * 底部应用
     */
    public static final String APP_BOTTOM="app_bottom";


    /**
     * 是否第一次开机
     */
    public static final String IS_FIRST_BOOT="is_firt_booot";


    public static final String CUSTOM_SHEET_FILE1="custom_sheet_file1";
    public static final String CUSTOM_SHEET_FILE2="custom_sheet_file2";
    public static final String CUSTOM_SHEET_FILE3="custom_sheet_file3";


    /**
     * 重启是否提示
     */
    public static final String IS_REBOOT_TIP="is_reboot_tip";


    /**
     * 网关设备虚拟id
     */
    public static final String GATE_WAY_DEV_ID="gate_way_id";


    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     */
    public static void put(Context context, String key, Object object)
    {
        LogUtils.Logd(TAG,"context == "+context);
        if(context==null||object==null){
            return;
        }
        LogUtils.Logd(TAG,"put  "+key+"   "+object);
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String)
        {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer)
        {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean)
        {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float)
        {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long)
        {
            editor.putLong(key, (Long) object);
        } else
        {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     */
    public static Object get(Context context, String key, Object defaultObject)
    {


        if(context==null){
            return "";
        }
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_MULTI_PROCESS);

        if (defaultObject instanceof String)
        {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer)
        {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean)
        {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float)
        {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long)
        {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某个key值已经对应的值
     */
    public static void remove(Context context, String key)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     */
    public static void clear(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     */
    public static boolean contains(Context context, String key)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_MULTI_PROCESS);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     */
    public static Map<String, ?> getAll(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_MULTI_PROCESS);
        return sp.getAll();
    }


    /**
     * 保存图片到SharedPreferences
     * @param mContext
     * @param imageView
     */
    public static void putImage(Context mContext, String key, ImageView imageView) {
        BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        // 将Bitmap压缩成字节数组输出流
        ByteArrayOutputStream byStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);
        // 利用Base64将我们的字节数组输出流转换成String
        byte[] byteArray = byStream.toByteArray();
        String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        // 将String保存shareUtils
        SharePreferenceUtils.put(mContext, key, imgString);
    }

    /**
     * 从SharedPreferences读取图片
     * @param mContext
     * @param imageView
     */
    public static Bitmap getImage(Context mContext, String key, ImageView imageView) {
        String imgString = (String) SharePreferenceUtils.get(mContext, key, "");
        if (!imgString.equals("")) {
            // 利用Base64将我们string转换
            byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT);
            ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray);
            // 生成bitmap
            return BitmapFactory.decodeStream(byStream);
        }
        return null;
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     */
    private static class SharedPreferencesCompat
    {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        private static Method findApplyMethod()
        {
            try
            {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e)
            {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         */
        public static void apply(SharedPreferences.Editor editor)
        {
            try
            {
                if (sApplyMethod != null)
                {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e)
            {
            } catch (IllegalAccessException e)
            {
            } catch (InvocationTargetException e)
            {
            }
            editor.commit();
        }
    }
}
